from sqlalchemy.orm.session import Session
import uuid
from sent.model.entities import EntBase
from sqlalchemy.types import Integer
from sqlalchemy.schema import Column
from sententialyzer.settings import DbSession
from sent.model.entities.user import Sequence_Generation

#USE THIS FOR DEBUG ONLY. Totally not optimized
USE_DUMMY_SEQUENCE_GENERATOR = False

class BaseDBManager():
    def __init__(self):
        if USE_DUMMY_SEQUENCE_GENERATOR:
            self.seq_db_session = DbSession()
        
    def commitSession(self):
        dbSession=self.dbSession
        assert isinstance(dbSession, Session)
        dbSession.commit()
    
    def closeSession(self):
        self.dbSession.close()
        
        if USE_DUMMY_SEQUENCE_GENERATOR:
            self.seq_db_session.close()
        
    def rollbackSession(self):
        self.dbSession.rollback()
        
    def expunge(self, obj):
        self.dbSession.expunge(obj)
        
    def paginateResults(self, q, offset, limit):
        assert offset >= 0 and limit > 0
        
        currentResults = q.offset(offset).limit(limit).all()
        currentResultsCnt = len(currentResults)
        if limit == currentResultsCnt:
            totalResultsCnt = q.count()
        else:
            totalResultsCnt = currentResultsCnt + offset
            
        return currentResults, totalResultsCnt 
    
    
    def generateUUID(self):
        if USE_DUMMY_SEQUENCE_GENERATOR:
            #USE THIS FOR DEBUG ONLY. Totally not optimized
            newSeqGen = Sequence_Generation()
            self.seq_db_session.add(newSeqGen)
            self.seq_db_session.commit()
            
            return uuid.UUID(int=newSeqGen.dummy_uuid)
        else:
            return uuid.uuid1()